package com.github.starrytop.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.digest.DigestUtils;

public class AESUtil {
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
    private static final String ALGORITHM = "AES";
    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * AES加密
     * @param key 加密/解密建
     * @param data 明文数据
     * @return 密文数据（16进制字符串）
     * @throws Exception 例外
     */
    public static String encrypt(String key, String data) throws Exception {

        if (key == null || data == null) {
            throw new IllegalArgumentException("both \"key\" and \"data\" must not be null.");
        }

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);

        SecretKeySpec secretKeySpec = new SecretKeySpec(DigestUtils.sha256(key), ALGORITHM);

        byte[] byteIv = new byte[cipher.getBlockSize()];
        IvParameterSpec ivParameterSpec = new IvParameterSpec(byteIv);

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

        String result = bytesToHex(cipher.doFinal(data.getBytes(DEFAULT_CHARSET)));
        return result;
    }

    /**
     * AES解密
     * @param key 加密/解密建
     * @param dataCrypt 密文数据（16进制字符串）
     * @return 明文数据
     * @throws Exception 例外
     */
    public static String decrypt(String key, String dataCrypt) throws Exception {

        if (key == null || dataCrypt == null) {
            throw new IllegalArgumentException("both \"key\" and \"dataCrypt\" must not be null.");
        }

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);

        SecretKeySpec secretKeySpec = new SecretKeySpec(DigestUtils.sha256(key), ALGORITHM);
        byte[] byteIv = new byte[cipher.getBlockSize()];

        IvParameterSpec ivParameterSpec = new IvParameterSpec(byteIv);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

        return new String(cipher.doFinal(hexToBytes(dataCrypt)), DEFAULT_CHARSET);
    }

    /**
     * 16进制字符串转字节数组
     * @param hexStr 16进制字符串
     * @return 字节数组
     */
    private static byte[] hexToBytes(String hexStr) {

        // 长度是偶数以外是不变换
        if ((hexStr == null) || (hexStr.length() % 2 != 0)) {
            return null;
        }

        int bytesLength = hexStr.length() / 2;
        byte[] result = new byte[bytesLength];

        for (int i = 0; i < bytesLength; i++) {
            result[i] = (byte) Integer.parseInt(hexStr.substring(2 * i, 2 * (i + 1)), 16);
        }

        return result;
    }

    /**
     * 字节数组转16进制字符串
     * @param bytes 字节数组
     * @return 16进制字符串
     */
    private static String bytesToHex(byte[] bytes){
        StringBuilder stringBuilder = new StringBuilder("");
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
